//
//  Holdings_TableVC.m
//  KaChing_App
//
//  Created by Jordan Robert Yust on 2/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Holdings_TableVC.h"
#import "Constants.h"
#import "AsyncImageView.h"

@implementation Holdings_TableVC

@synthesize curStockArray;
@synthesize segmentedControl;
@synthesize activityIndicator;
@synthesize stockTickerLabel;
@synthesize currentPriceLabel;
@synthesize currentPriceChangeLabel;
@synthesize actionLabel;
@synthesize quantityLabel;
@synthesize dataManager;
@synthesize portfolio;
@synthesize pendingOrders;


/*
 - (id)initWithStyle:(UITableViewStyle)style {
 // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 if (self = [super initWithStyle:style]) {
 }
 return self;
 }
 */


// Implement viewDidLoad to do additional setup after loading the view.
- (void)viewDidLoad
{
	NSLog(@"\n\nInside Holdings Thing!!\nRemotekey: %@\nUserID: %d", [dataManager remoteKey], [dataManager userID]);
	
	/* Obtain all stock information from Kaching using the DataManager */
	self.refreshHoldings;
	
	/* Specifies the method (@selector(...)) that will be called when events happen to the segmentedControl */
	[segmentedControl       addTarget:self
							action:@selector(segmentedControlButtonPressed:)
							forControlEvents:UIControlEventValueChanged
	 ];
	
	currentSecond_Column = stockPriceIndex;
	
	/* When the view is first loaded, display Long holdings */
	[self getLongHoldingsArray];
	
    [super viewDidLoad];
}


/*
 ------------------------------------------------------------------------
 UITableViewDataSource Protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITableViewDataSource Protocol methods

/*
 This method specifies how many sections there to be in the table.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}


/*
 This method specifies the number of rows for each section.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [curStockArray count];
}

/*
 This method creates/modifies the cell at the specified index in the tableView.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 The 'tableView' parameter is the actual UITableView object.
 The 'indexPath' parameter is the index in the tableView
 */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
	[currencyFormatter setPositiveFormat:@"#,##0.00"];
	[currencyFormatter setNegativeFormat:@"#,##0.00"];
	
	NSNumberFormatter *quantityFormatter = [[NSNumberFormatter alloc] init];
	[quantityFormatter setPositiveFormat:@"###,###,##0"];
	[quantityFormatter setNegativeFormat:@"###,###,##0"];
	
	static NSString *CellIdentifier = @"Cell";
	UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
	
	//check to see if we are displaying stocks or pending orders
	if ([segmentedControl selectedSegmentIndex] != pendingOrdersSegment) //Stocks
	{
		/* If the current cell hasn't been created yet */
		if (cell == nil)
		{
			//If you want the label color to be GRAY then specify the UILabel to be GRAY. In this case every label is set to default color = WHITE
			
			/* Create the cell */
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
										   reuseIdentifier:CellIdentifier] autorelease];
			
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			if (indexPath.row % 2 == 0){
				cell.contentView.backgroundColor = [UIColor customLightGray];
			}
			else
			{
				cell.contentView.backgroundColor = [UIColor whiteColor];
			}
			
			/* Memory Management: release label prior to recreating it */
			[stockTickerLabel release];
			
			/* Create the Stock Ticker label and add it to the cell */
			stockTickerLabel = [[UILabel alloc] initWithFrame:ticker];
			stockTickerLabel.textAlignment = UITextAlignmentLeft;
			stockTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"ticker"]];
			stockTickerLabel.font = [UIFont boldSystemFontOfSize:16.0];
			stockTickerLabel.backgroundColor = [UIColor clearColor];			
			stockTickerLabel.tag = stockTickerLabel_Tag;
			[cell.contentView addSubview:stockTickerLabel];
		
			/* Memory Management: release label prior to recreating it */
			[currentPriceLabel release];
			
			/* Create the Current Price label and add it to the cell */
			currentPriceLabel = [[UILabel alloc] initWithFrame:price];
			currentPriceLabel.textAlignment = UITextAlignmentRight;
			currentPriceLabel.backgroundColor = [UIColor clearColor];
			currentPriceLabel.lineBreakMode = UILineBreakModeWordWrap;			
			currentPriceLabel.font = [UIFont boldSystemFontOfSize:16.0];
			currentPriceLabel.lineBreakMode = UILineBreakModeWordWrap;
			currentPriceLabel.tag = currentPriceLabel_Tag;
			
			/* If the stock prices should be displayed */
			if (currentSecond_Column == stockPriceIndex)
				currentPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"$%@  ",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]]]]];

			/* If the number of shares for the stock should be displayed */
			else if (currentSecond_Column == numShareIndex)
				currentPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@ shares",[quantityFormatter stringFromNumber:[NSNumber numberWithDouble:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] doubleValue]]]]];
			
			/* If the total price (price * shares) should be displayed */
			else
			{
				NSNumber *stockPrice = [NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]];
				NSNumber *numShares = [NSNumber numberWithDouble:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] doubleValue]];
				
				currentPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"$%@ total", [currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[stockPrice floatValue]*[numShares doubleValue]]]]];
			}

			[cell.contentView addSubview:currentPriceLabel];
			
			/* Memory Management: release label prior to recreating it */
			[currentPriceChangeLabel release];
			
			/* Create the Current Price Change label and add it to the cell */
			currentPriceChangeLabel = [[UILabel alloc] initWithFrame:prChange];
			currentPriceChangeLabel.textAlignment = UITextAlignmentLeft;
			currentPriceChangeLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastChange"] floatValue]]]]];
			if ([currentPriceChangeLabel.text floatValue] <= 0){
				currentPriceChangeLabel.textColor = [UIColor redColor];
			}
			else{
				currentPriceChangeLabel.textColor = [UIColor customGreen];
			}
			currentPriceChangeLabel.backgroundColor = [UIColor clearColor];
			currentPriceChangeLabel.lineBreakMode = UILineBreakModeWordWrap;			
			currentPriceChangeLabel.font = [UIFont boldSystemFontOfSize:10.0];
			currentPriceChangeLabel.lineBreakMode = UILineBreakModeWordWrap;
			currentPriceChangeLabel.tag = currentPriceChangeLabel_Tag;
			[cell.contentView addSubview:currentPriceChangeLabel];
			
			/* Memory Management: release label prior to recreating it */
			//[currentPercentChangeLabel release];
			
			/* Create the Current Percentage Price Change label and add it to the cell */
			//currentPercentChangeLabel = [[UILabel alloc] initWithFrame: CGRectMake(240.0, 12.0,80, 25.0)];
			//currentPercentChangeLabel.textAlignment = UITextAlignmentCenter;
			//currentPercentChangeLabel.backgroundColor = [UIColor clearColor];
			//currentPercentChangeLabel.tag = currentPercentChangeLabel_Tag;
			//[cell.contentView addSubview:currentPercentChangeLabel];
		}
		/* The cell already exists (i.e., we are updating the content of an already-existing cell */
		else {
			
			//This tells obsolete images that they should be removed once the new one is finished downloading
			AsyncImageView* oldImage = (AsyncImageView*)[cell.contentView viewWithTag:999];
			[oldImage removeFromSuperview];
			
			if (indexPath.row % 2 == 0){
				cell.contentView.backgroundColor = [UIColor customLightGray];
			}
			else{
				cell.contentView.backgroundColor = [UIColor whiteColor];
			}
			
			/* Retrieve the new Stock Ticker and assign it to the stock ticker label */
			UILabel *tempTickerLabel = (UILabel *) [cell.contentView viewWithTag:stockTickerLabel_Tag];
			tempTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"ticker"]];
			
			/* Retrieve the current price of the new Stock and assign it to the current price label */
			UILabel *tempPriceLabel = (UILabel *) [cell.contentView viewWithTag:currentPriceLabel_Tag];
			
			/* If the stock price should be displayed */
			if (currentSecond_Column == stockPriceIndex)
				tempPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"$%@  ",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]]]]];

			/* If the number of shares of the stock should be displayed */
			else if (currentSecond_Column == numShareIndex)
				tempPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@ shares",[quantityFormatter stringFromNumber:[NSNumber numberWithDouble:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] doubleValue]]]]];

			/* If the total cost (price * shares) should be displayed */
			else
			{
				NSNumber *stockPrice = [NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastPrice"] floatValue]];
				NSNumber *numShares = [NSNumber numberWithDouble:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] doubleValue]];
				
				tempPriceLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"$%@ total", [currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[stockPrice floatValue]*[numShares doubleValue]]]]];
			}
			
			/* Retrieve the current price change of the new Stock and assign it to the current price change label */
			UILabel *tempChangeLabel = (UILabel *) [cell.contentView viewWithTag:currentPriceChangeLabel_Tag];
			tempChangeLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"%@",[currencyFormatter stringFromNumber:[NSNumber numberWithFloat:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastChange"] floatValue]]]]];
			if ([tempChangeLabel.text floatValue] < 0){
				tempChangeLabel.textColor = [UIColor redColor];
			}
			else{
				tempChangeLabel.textColor = [UIColor customGreen];
			}
			/* Retrieve the current percentage price change of the new Stock and assign it to the current percentage price change label */
			//UILabel *tempPercentChangeLabel = (UILabel *) [cell.contentView viewWithTag:currentPercentChangeLabel_Tag];
			//tempPercentChangeLabel.text = [self checkDisplayString:[(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"lastChange"] stringValue]];
		}
		
		/*Code to add in the new image to the cell*/
		//Create new frome for the image
		CGRect frame;
		
		//specify frame size
		frame.size.width=20; frame.size.height=20;
		
		//specify location of frame within cell
		frame.origin.x=0; frame.origin.y=5;
		
		//create a new asynchronous image object 
		AsyncImageView* asyncImage = [[[AsyncImageView alloc]
									   initWithFrame:frame] autorelease];
		
		//set the tag so that we know the image has been added
		asyncImage.tag = 999;
		
		//get the stock image url
		if([[curStockArray objectAtIndex:indexPath.row] valueForKey:@"companyIconUrl"]!= NULL)
		{
			NSURL* url = [NSURL URLWithString:(NSString *) [[curStockArray objectAtIndex:indexPath.row] valueForKey:@"companyIconUrl"]];
		
			[asyncImage loadImageFromURL:url];
		
			[cell.contentView addSubview:asyncImage];
		}
		
	}
	else //pending orders
	{
		/* If the current cell hasn't been created yet */
		if (cell == nil)
		{
			
			/* Create the cell */
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
										   reuseIdentifier:CellIdentifier] autorelease];
			
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			
			if (indexPath.row % 2 == 0){
				cell.contentView.backgroundColor = [UIColor customLightGray];
			}
			else{
				cell.contentView.backgroundColor = [UIColor whiteColor];
			}
			
			/* Memory Management: release label prior to recreating it */
			[stockTickerLabel release];
			
			/* Create the Stock Ticker label and add it to the cell */
			stockTickerLabel = [[UILabel alloc] initWithFrame:ticker];
			stockTickerLabel.textAlignment = UITextAlignmentLeft;
			stockTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"symbol"]];
			stockTickerLabel.font = [UIFont boldSystemFontOfSize:16.0];
			stockTickerLabel.backgroundColor = [UIColor clearColor];
			stockTickerLabel.tag = stockTickerLabel_Tag;
			[cell.contentView addSubview:stockTickerLabel];
			
			/* Memory Management: release label prior to recreating it */
			[quantityLabel release];
			
			/* Create the Quantity label and add it to the cell */
			quantityLabel = [[UILabel alloc] initWithFrame:price];
			quantityLabel.textAlignment = UITextAlignmentRight;
			quantityLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"Num Shares: %@", [(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] stringValue]]];
			quantityLabel.textColor = [UIColor blackColor];
			quantityLabel.backgroundColor = [UIColor clearColor];
			quantityLabel.lineBreakMode = UILineBreakModeWordWrap;			
			quantityLabel.font = [UIFont boldSystemFontOfSize:16.0];
			quantityLabel.lineBreakMode = UILineBreakModeWordWrap;
			quantityLabel.tag = quantityLabel_Tag;
			[cell.contentView addSubview:quantityLabel];
			
			/* Memory Management: release label prior to recreating it */
			[actionLabel release];
			
			/* Create the Current Action label and add it to the cell */
			actionLabel = [[UILabel alloc] initWithFrame:prChange];
			actionLabel.textAlignment = UITextAlignmentLeft;
			actionLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"action"]];
			actionLabel.backgroundColor = [UIColor clearColor];
			actionLabel.lineBreakMode = UILineBreakModeWordWrap;			
			actionLabel.font = [UIFont boldSystemFontOfSize:10.0];
			actionLabel.lineBreakMode = UILineBreakModeWordWrap;
			actionLabel.tag = actionLabel_Tag;
			[cell.contentView addSubview:actionLabel];
			
		}
		/* The cell already exists (i.e., we are updating the content of an already-existing cell */
		else
		{
			
			if (indexPath.row % 2 == 0){
				cell.contentView.backgroundColor = [UIColor customLightGray];
			}
			else{
				cell.contentView.backgroundColor = [UIColor whiteColor];
			}
			
			/* Retrieve the new Stock Ticker and assign it to the stock ticker label */
			UILabel *tempTickerLabel = (UILabel *) [cell.contentView viewWithTag:stockTickerLabel_Tag];
			tempTickerLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"symbol"]];			
			
			/* Retrieve the current action of the new order and assign it to the action label */
			UILabel *tempActionLabel = (UILabel *) [cell.contentView viewWithTag:actionLabel_Tag];
			tempActionLabel.text = [self checkDisplayString:[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"action"]];
			
			/* Retrieve the current price change of the new Stock and assign it to the current price change label */
			UILabel *tempQuantityLabel = (UILabel *) [cell.contentView viewWithTag:quantityLabel_Tag];
			tempQuantityLabel.text = [self checkDisplayString:[NSString stringWithFormat:@"Num Shares: %@", [(NSNumber *)[(NSMutableDictionary *)[curStockArray objectAtIndex:indexPath.row] valueForKey:@"quantity"] stringValue]]];
			tempQuantityLabel.textColor = [UIColor blackColor];
		}
		
		//Create new frome for the image
		CGRect frame;
		
		//specify frame size
		frame.size.width=20; frame.size.height=20;
		
		//specify location of frame within cell
		frame.origin.x=0; frame.origin.y=5;

		UIView* blank = [[UILabel alloc] initWithFrame:frame];
		//set the proper background color to match the cell
		blank.backgroundColor = cell.contentView.backgroundColor;
		//add a blank image to replace the asynchronous image if one is there 
		[cell.contentView addSubview:blank];
		}
		/* Return the newly created (or newly updated) cell */
	return cell;
	
	/* Memory Management: These were both allocated at the start of this method, therefore release them */
	[currencyFormatter release];
	[quantityFormatter release];
}

/*
 This method specifies the Header of the current section in the tableView.
 NOTE: This method is part of the UITableViewDataSource Protocol.
 */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	if ([segmentedControl selectedSegmentIndex] == pendingOrdersSegment)
		return @"Pending Orders";
	else if ([segmentedControl selectedSegmentIndex] == shortHoldingsSegment)
		return @"Short Holdings";
	else if ([segmentedControl selectedSegmentIndex] == longHoldingsSegment)
		return @"Long Holdings";
	else
		return @"No clue!";
}

/*
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 }
 if (editingStyle == UITableViewCellEditingStyleInsert) {
 }
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 return YES;
 }
 */

/*
 ------------------------------------------------------------------------
 UITableViewDelegate Protocol methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UITableViewDelegate Protocol methods

/*
 This method is called whenever an entry in a TableView is selected.
 NOTE: This method is part of the UITableViewDelegate Protocol.
 The 'tableView' parameter is the actual TableView object.
 The 'indexPath' parameter is the index of the row that was selected in the tableView
 */

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if (currentSecond_Column < totalCashIndex)
		currentSecond_Column++;
	else
		currentSecond_Column = stockPriceIndex;
	
	[tableView reloadData];
}


/*
 ------------------------------------------------------------------------
UserDefined methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark UserDefined methods


/*
 This method is called when a segment in the SegmentedControl object is pressed.  It updates
 the tableView with the stock information corresponding to the pressed segment.
 */
- (void) segmentedControlButtonPressed:(UISegmentedControl *)control
{
	/* If the parameter corresponds to this class' segmentedControl object (should always be the case).. */
	if (control == segmentedControl)
	{
		/* If the segment that was pressed corresponds to pending orders */
		if (segmentedControl.selectedSegmentIndex == pendingOrdersSegment)
		{
			[self getPendingOrdersArray];
			
			/* Update the contents of the table */
			[self.tableView reloadData];
		}
		/* If the segment that was pressed corresponds to short Holdings */
		else if (segmentedControl.selectedSegmentIndex == shortHoldingsSegment)
		{
			[self getShortHoldingsArray] ;
			
			/* Update the contents of the table */
			[self.tableView reloadData];
			
		}
		/* If the segment that was pressed corresponds to long Holdings */
		else if (segmentedControl.selectedSegmentIndex == longHoldingsSegment)
		{
			[self getLongHoldingsArray];
			
			/* Update the contents of the table */
			[self.tableView reloadData];
		}
		/* If the segment that was pressed doesn't correspond to the above 3 options (should never be entered) */
		else
			NSLog(@"The index that was pressed was: %d", segmentedControl.selectedSegmentIndex);
	}
}

/*
 This method obtains the pending orders for the current portfolio and stores them in the current array of stocks (instance variable)
 */
- (void)getPendingOrdersArray
{
	NSLog(@"getPendingOrdersArray METHOD ENTERED!!!");
	NSLog(@"Pending Orders Dictiionary: %@", pendingOrders);

	/* Memory Management: Release object prior to reassigning it */
	[curStockArray release];

	//set the current array to be the orders array
	curStockArray = [[pendingOrders objectForKey:@"orders"] retain];
	
	NSLog(@"getPendingOrdersArray METHOD EXITING!!!");
}

/*
 This method obtains the Short Holdings for the current portfolio and stores them in the current array of stocks (instance variable)
 */
- (void) getShortHoldingsArray
{
	NSDictionary *shortHoldingsDictionary = [portfolio objectForKey:@"shortHoldings"];	// Obtains the dictionary of shortHoldings
	NSMutableArray *shortStockArray = [[NSMutableArray alloc] init];	// Create the array to store the Stock dictionaries
	
	NSArray *shortStockNames_Unsorted = [shortHoldingsDictionary allKeys];	// Get all short stocks in portfolio (unsorted)
	
	/* Sort the stocks in alphabetical order and store them in another array */
	NSArray *shortStockNames_Sorted = [shortStockNames_Unsorted sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	
	/* Loop through all stocks in the dictionary */
	for(int i = 0; i < [shortStockNames_Sorted count]; i++)
	{
		NSString *key = [shortStockNames_Sorted objectAtIndex:i];
		
		/* Add the Stock as a MutableDictionary to the array of stocks */
		[shortStockArray addObject:(NSMutableDictionary *)[shortHoldingsDictionary objectForKey:key]];
		
		/* Add a new key to the Stock: key = ticker, value = The stock's name */
		[(NSMutableDictionary *)[shortHoldingsDictionary objectForKey:key] setObject:key forKey:@"ticker"];
	}
	
	/* Memory Management: Release object prior to reassigning it */
	[curStockArray release];
	
	/* Assign the curStockArray to be the array of short stocks */
	curStockArray = [shortStockArray retain];       // after this, curStockArray retain count = 2 (because the other array has control over it too)
	[shortStockArray release];                      // after this, curStockArray retain count = 1 (which is what it needs to be)
	
	NSLog(@"getShortHoldingsArray METHOD EXITING!!!");
	
}

/*
 This method obtains the Long Holdings for the current portfolio and stores them in the current array of stocks (instance variable)
 */
- (void)getLongHoldingsArray
{
	NSDictionary *longHoldingsDictionary = [portfolio objectForKey:@"longHoldings"];	// Obtains the dictionary of longHoldings
	NSMutableArray *longStockArray = [[NSMutableArray alloc] init];		// Create the array to store the Stock dictionaries
	
	NSArray *longStockNames_Unsorted = [longHoldingsDictionary allKeys];	// Get all long stocks in portfolio (unsorted)
	
	/* Sort the stocks in alphabetical order and store them in another array */
	NSArray *longStockNames_Sorted = [longStockNames_Unsorted sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
	
	/* Loop through all stocks in the dictionary */
	for(int i = 0; i < [longStockNames_Sorted count]; i++)
	{
		NSString *key = [longStockNames_Sorted objectAtIndex:i];
		
		/* Add the Stock as a MutableDictionary to the array of stocks */
		[longStockArray addObject:(NSMutableDictionary *)[longHoldingsDictionary objectForKey:key]];
		
		/* Add a new key to the Stock: key = ticker, value = The stock's name */
		[(NSMutableDictionary *)[longHoldingsDictionary objectForKey:key] setObject:key forKey:@"ticker"];
	}
	
	/* Assign the curStockArray to be the array of long stocks */
	curStockArray = [longStockArray retain];	// after this, curStockArray retain count = 2 (because the other array has control over it too)
	[longStockArray release];					// after this, curStockArray retain count = 1 (which is what it needs to be)
	
	NSLog(@"getLongHoldingsArray METHOD EXITING!!!");

}

/*
 Checks a string to be displayed to determine whether the string is null.
 If the string is null, then it changes it to -- for display purposes.
*/
-(NSString *) checkDisplayString:(NSString *) data
{
	if(data == nil)
	{
		return @"--";
	}
	else
	{
		return data;
	}
}

/*
 ------------------------------------------------------------------------
IBAction methods
 ------------------------------------------------------------------------
 */

#pragma mark -
#pragma mark IBAction methods

/*
 This method retrieves the stock information of the user portfolio specified in the DataManager object.  It updates all
 stock information for the user, and stores the results in the appropriate variables.
 */
- (IBAction) refreshHoldings
{
	/* Creates an ActivityIndicator and adds it to the middle of the screen */
	CGRect frame = CGRectMake(140.0, 200.0, activityIndicatorySize, activityIndicatorySize);
	UIActivityIndicatorView *progressInd = [[UIActivityIndicatorView alloc] initWithFrame:frame];          
	progressInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	[self.navigationController.view addSubview:progressInd];
	
	[progressInd startAnimating];   // Start the animation of the ActivityIndicator
	
	/* If the DataManager exists (should always be the case if this method is called)... */
	if (dataManager != nil)
	{
		NSLog(@"\nINSIDE REFRESH HOLDINGS METHOD!!\n");
		
		/* Release all objects before assigning them to new values */
		[portfolio release];
		[pendingOrders release];
		
		/* Retrieve all stock information. NOTE: This is what actually performs the Kaching network call */
		portfolio = [[dataManager getPortfolio] retain];
		pendingOrders = [[dataManager getPendingOrders] retain];
		
	}
	
	// Stop the animation of and release the ActivityIndicator
	[progressInd stopAnimating];
	[progressInd release];
	
	//based on the segmented control button that is selected update current array with the corresponding data
	if ([segmentedControl selectedSegmentIndex] == pendingOrdersSegment)
		[self getPendingOrdersArray];
	else if ([segmentedControl selectedSegmentIndex] == shortHoldingsSegment)
		[self getShortHoldingsArray];
	else if ([segmentedControl selectedSegmentIndex] == longHoldingsSegment)
		[self getLongHoldingsArray];
	else
		NSLog(@"Uh Oh!");
	
	[self.tableView reloadData];
	
	NSLog(@"\nEXITING REFRESH HOLDINGS METHOD!!\n");
}

/*
 ------------------------------------------------------------------------
 System methods
 ------------------------------------------------------------------------
 */

#pragma mark -

/* This method is entered before the view appears each time */
//- (void)viewWillAppear:(BOOL)animated
//{
//	NSLog(@"Holdings view!!! - The viewWillAppear method!");
//	
//	/* Refreshes the holdings in order to display the most current list */
//	[self refreshHoldings];
//	
//	[super viewWillAppear:animated];
//}
 
/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */
/*
 - (void)viewWillDisappear:(BOOL)animated {
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 }
 */
/*
 - (void)didReceiveMemoryWarning {
 [super didReceiveMemoryWarning];
 }
 */

- (void)dealloc
{
	/* Release all objects */
	[curStockArray release];
	[segmentedControl release];
	[activityIndicator release];
	[stockTickerLabel release];
	[currentPriceLabel release];
	[currentPriceChangeLabel release];
	[actionLabel release];
	[quantityLabel release];
	[dataManager release];
	[portfolio release];
	[pendingOrders release];
    [super dealloc];
}

@end

